import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import utils from '@/utils/utils.ts';
import request from '@/utils/request.ts';

const router = createRouter({
  // history: createWebHistory(),//历史模式
  history: createWebHashHistory(),//hash模式
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/main',
      name: 'main',
      meta: {
        requiresAuth: true, // 需要登录
      },
      component: () => import('../views/Home.vue'),
    },
    {
      path: '/404',
      component: () => import('../views/pub/NotFound.vue'),
      name: '404',
    },
  ],
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth); // 检查目标路由是否需要认证
  if(requiresAuth) {
    // 需要认证
    // const authStore = window.localStorage.getItem("scap_token"); // 获取认证状态
    // if(authStore) {
    //   // 已认证
    //   next();
    // } else {
    //   // 认证状态为空
    //   next({ name: 'login' });
    // }
    const urlParams = window.location.href;
    if (urlParams.indexOf('?token') > -1 || urlParams.indexOf('?sid') > -1) {
      const str = urlParams.substr(urlParams.indexOf('?') + 1); // 从第一个字符开始 因为第0个是?号 获取所有除问号的所有符串
      const strs = str.split('=');
      let token = '';
      let sid = '';
      if (strs[1].indexOf('#/main') > -1) {
        token = strs.length > 0 && strs[0] == 'token' ? strs[1].substr(0, strs[1].indexOf('#')) : '';
        sid = strs.length > 0 && strs[0] == 'sid' ? strs[1].substr(0, strs[1].indexOf('#')) : '';
      } else {
        token = strs.length > 0 && strs[0] == 'token' ? strs[1] : '';
        sid = strs.length > 0 && strs[0] == 'sid' ? strs[1] : '';
      }
      const action = {
        token: '',
        sid: '',
      };
      if (token) {
        action.token = token;
      } else if (sid) {
        action.sid = sid;
      }
      request.rpc({ name: 'protect.employee.SilenceLogin', action }).then((res: any) => {
        if (res.accessToken) {
          const arr = res.accessToken.split('=');
          const key = arr[0];
          const value = arr[1];
          window.localStorage.setItem(key, value);
        }
        utils.getLoginStatus().then((result: any) => {
          if (result.user) {
            window.localStorage.setItem('User', JSON.stringify(result.user));
            next();
          } else {
            next({ path: '/login' });
          }
        }).catch((err: any) => {
          next({ path: '/login' });
        });
      });
    } else {
      utils.getLoginStatus().then((result: any) => {
        if (result.user) {
          window.localStorage.setItem('User', JSON.stringify(result.user));
          next();
        } else {
          next({ path: '/login' });
        }
      }).catch((err: any) => {
        next({ path: '/login' });
      });
    }
  } else {
    // 否则继续导航
    next();
  }
});

export default router